<template>
    <el-dialog
        :title="!dataForm.id ? $t('handle.add') : $t('handle.update')"
        :close-on-click-modal="false"
        :before-close="handleDialogClose"
        :visible.sync="visible">
    <div v-loading = loading>
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="150px">
      <el-form-item label="所属社区/居委会" prop="neighborhoodCommitteeCode">
        <el-cascader v-model="address" ref="cascaderAddress"  :options="options" @click.native="getCountry" @active-item-change="getNodes" :props="props" style="width: 100%"></el-cascader>
        <!-- <el-input v-model="dataForm.communityCode" placeholder="所属社区"></el-input> -->
      </el-form-item>
      <el-form-item label="网格名称" prop="name">
        <el-input v-model="dataForm.name" placeholder="网格名称"></el-input>
      </el-form-item>
      <el-form-item label="网格员" prop="manager">
        <el-input v-model="dataForm.manager" placeholder="网格员姓名"></el-input>
      </el-form-item>
      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="dataForm.phone" placeholder="网格员联系电话"></el-input>
      </el-form-item>
    </el-form>
    <div style="text-align:right;">
    <span slot="footer" class="dialog-footer">
      <el-button @click="callOf()">{{ $t('handle.cancel') }}</el-button>
      <el-button type="primary" @click="dataFormSubmit()">{{ $t('handle.confirm') }}</el-button>
    </span>
    </div>
  </div>
  </el-dialog>

</template>
<script>
import { isMobile } from "@/utils/validate";
export default {
  data() {
    // 手机号验证
    var validateMobile = (rule, value, callback) => {
      if (!isMobile(value)) {
        callback(new Error("手机号格式错误"));
      } else {
        callback();
      }
    };
    let checkNeighborhoodCommitteeCode = (rule, value, callback) => {
      if (typeof this.address[this.address.length - 1] === "undefined") {
        callback(new Error("社区/居委会不能为空"));
      } else {
        callback();
      }
    };
    return {
      loading: false,
      address: [],
      visible: false,
      dataForm: {
        id: "",
        name: "",
        communityCode: "",
        neighborhoodCommitteeCode: "",
        manager: "",
        phone: ""
      },
      options: [],
      props: {
        value: "id",
        label: "name",
        children: "children"
      },
      dataRule: {
        name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
        manager: [
          { required: true, message: "网格员不能为空", trigger: "blur" }
        ],
        phone: [
          {
            required: true,
            message: "网格员联系电话不能为空",
            trigger: "blur"
          },
          { validator: validateMobile, trigger: "blur" }
        ],
        neighborhoodCommitteeCode: [
          {
            required: true,
            validator: checkNeighborhoodCommitteeCode,
            trigger: "blur"
          }
        ]
      }
    };
  },
  created() {
    // this.getCountry()
  },
  methods: {
    getNodes(val) {
      if (val.length === 1) {
        this.getProviceCode(val[0]);
      } else if (val.length === 2) {
        this.getCityCode(val[0], val[1]);
      } else if (val.length === 3) {
        this.getAreaCode(val[0], val[1], val[2]);
      } else if (val.length === 4) {
        this.getCommunityCode(val[0], val[1], val[2], val[3]);
      } else if (val.length === 5) {
        this.getNeighborhoodCommitteeCode(
          val[0],
          val[1],
          val[2],
          val[3],
          val[4]
        );
      }
    },
    getCountry(regionId, type) {
      this.$http({
        url: `/dg-standard-info/dgstandardregion/list`,
        method: "post",
        params: { regionId: 0, type: 11 }
      }).then(({ data }) => {
        if (data && data.code === 0) {
          data.page.map(item => {
            this.$set(item, "name", item.name);
            this.$set(item, "children", []);
          });
          this.options = data.page;
        }
      });
    },
    // 获取省份
    getProviceCode(countryId) {
      this.$http({
        url: `/dg-standard-info/dgstandardregion/list`,
        method: "post",
        params: { regionId: countryId, type: 12 }
      }).then(({ data }) => {
        if (data && data.code === 0) {
          data.page.map(item => {
            this.$set(item, "name", item.name);
            this.$set(item, "children", []);
          });
          this.options.map(item => {
            if (item.id === countryId) {
              item.children = data.page;
            }
          });
        }
      });
    },
    // 获取市
    getCityCode(countryId, provinceId) {
      this.$http({
        url: `/dg-standard-info/dgstandardregion/list`,
        method: "post",
        params: { regionId: provinceId, type: 13 }
      }).then(({ data }) => {
        if (data && data.code === 0) {
          data.page.map(item => {
            this.$set(item, "name", item.name);
            this.$set(item, "children", []);
          });
          this.options.map((item, i) => {
            if (item.id === countryId) {
              item.children.map((city, id) => {
                city.children = data.page;
              });
            }
          });
        }
      });
    },
    // 获取区
    getAreaCode(countryId, provinceId, cityId) {
      this.$http({
        url: `/dg-standard-info/dgstandardregion/list`,
        method: "post",
        params: { regionId: cityId, type: 23 }
      }).then(({ data }) => {
        if (data && data.code === 0) {
          data.page.map(item => {
            this.$set(item, "name", item.name);
            this.$set(item, "children", []);
          });
          this.options.map((item, i) => {
            if (item.id === countryId) {
              item.children.map((provice, idx) => {
                if (provice.id === provinceId) {
                  provice.children.map((city, ids) => {
                    city.children = data.page;
                  });
                }
              });
            }
          });
        }
      });
    },
    // 获取社区
    getCommunityCode(countryId, provinceId, cityId, areaId) {
      this.$http({
        url: `/dg-standard-info/dgstandardregion/list`,
        method: "post",
        params: { regionId: areaId, type: 32 }
      }).then(({ data }) => {
        if (data && data.code === 0) {
          data.page.map(item => {
            this.$set(item, "name", item.name);
            // this.$set(item, "children", []);
          });
          this.options.map((item, i) => {
            if (item.id === countryId) {
              item.children.map((provice, idx) => {
                if (provice.id === provinceId) {
                  provice.children.map((city, ids) => {
                    if (city.id === cityId) {
                      city.children.map((area, aid) => {
                        area.children = data.page;
                      });
                    }
                  });
                }
              });
            }
          });
        }
      });
    },
    // 获取居委会 社区id
    getNeighborhoodCommitteeCode(
      countryId,
      provinceId,
      cityId,
      areaId,
      communityCodeId
    ) {
      this.$http({
        url: `/dg-standard-info/dgstandardregion/list`,
        method: "post",
        params: { regionId: communityCodeId, type: 32 }
      }).then(({ data }) => {
        if (data && data.code === 0) {
          data.page.map(item => {
            this.$set(item, "name", item.name);
            // this.$set(item, "children", []);
          });
          this.options.map((item, i) => {
            if (item.id === countryId) {
              item.children.map((provice, idx) => {
                if (provice.id === provinceId) {
                  provice.children.map((city, ids) => {
                    if (city.id === cityId) {
                      city.children.map((area, aid) => {
                        if (area.id === areaId) {
                          area.children.map((communt, ic) => {
                            communt.children = data.page;
                          });
                        }
                      });
                    }
                  });
                }
              });
            }
          });
        }
      });
    },
    init(id) {
      this.visible = true;
      this.dataForm.id = id || 0;
      if (this.dataForm.id) {
        this.$http({
          url: `/dg-ic/ic/gridding/info/${this.dataForm.id}`,
          method: "get",
          params: this.$http.adornParams()
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.dataForm.name = data.data.name;
            // this.dataForm.communityCode = data.data.communityCode
            // this.dataForm.neighborhoodCommitteeCode = data.data.neighborhoodCommitteeCode
            this.options = [
              {
                id: data.data.neighborhoodCommitteeCode,
                name: data.data.neighborhoodCommitteeCodeName
              }
            ];
            this.address = [data.data.neighborhoodCommitteeCode];
            this.dataForm.manager = data.data.manager;
            this.dataForm.phone = data.data.phone;
          }
        });
      }
    },
    callOf() {
      this.visible = false;
      this.$refs[`dataForm`].resetFields();
      this.address = [];
      let obj = {};
      obj.stopPropagation = () => {};
      this.$refs.cascaderAddress.clearValue(obj);
    },
    handleDialogClose() {
      this.visible = false;
      this.$refs[`dataForm`].resetFields();
      let obj = {};
      obj.stopPropagation = () => {};
      this.$refs.cascaderAddress.clearValue(obj);
    },
    dataFormSubmit() {
      this.$refs["dataForm"].validate(validate => {
        if (validate) {
          this.loading = true;
          this.$http({
            url: `/dg-ic/ic/gridding/${!this.dataForm.id ? "save" : "update"}`,
            method: "post",
            data: this.$http.adornData({
              id: this.dataForm.id || undefined,
              name: this.dataForm.name,
              communityCode: this.address[this.address.length - 2],
              neighborhoodCommitteeCode: this.address[this.address.length - 1],
              manager: this.dataForm.manager,
              phone: this.dataForm.phone,
              createBy: this.$store.state.user.id,
              updateBy: this.$store.state.user.id
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.loading = false;
                  this.visible = false;
                  this.$emit("refreshDataList");
                  this.$refs[`dataForm`].resetFields();
                  this.address = [];
                }
              });
            } else {
              this.$message.error(data.msg);
              this.loading = false;
            }
          });
        }
      });
    }
  }
};
</script>
